package com.lottery.controller.qiuqiu.accoutController;


import com.alibaba.fastjson.JSONObject;
import com.lottery.controller.BaseController;
import com.lottery.dto.ResultDto;
import com.lottery.dto.UtilsDto;
import com.lottery.service.qiuqiu.accoutService.LocalauthService;
import com.lottery.service.qiuqiu.accoutService.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@RestController
@CrossOrigin
public class UserController extends BaseController {
    @Autowired
    private UserService userservice;

    @Autowired
    private LocalauthService localauthservice;


    /**
     * 用户登录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/user/public/login", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public String Login(HttpServletRequest request) {
        JSONObject jObject = new JSONObject();
        try {
            long starttime = System.currentTimeMillis();
            String body = readHttpBody(request);
            String hostAddr = request.getRemoteAddr();
            logger.info("********Login in********:" + body);
            JSONObject obj = JSONObject.parseObject(body);

            int loginType = obj.getInteger("loginType") == null ? 0 : obj.getInteger("loginType");
            String deviceId = obj.getString("deviceId");
            String phoneNum = obj.getString("username");
            String password = obj.getString("password");
            if (loginType == 1) { // 游客登录
                String loaclauth = localauthservice.login(phoneNum, "", deviceId, hostAddr, loginType);
                return loaclauth;
            }

            logger.info("phone_num:{},password:{},deviceId:{}, hostAddr:{}", phoneNum, password, deviceId, hostAddr);

            String loaclauth = localauthservice.login(phoneNum, password, deviceId, hostAddr, loginType);
            long endtime = System.currentTimeMillis();
            logger.info("********Login out[chargetime {}ms]********:{}", endtime - starttime, loaclauth);
            return loaclauth;
        } catch (Exception e) {
            logger.error("*****Login error******:", e);
            jObject.put("result", "1");
            jObject.put("msg", "异常");
        }
        return jObject.toJSONString();
    }

    /**
     * 用户注册
     */
    @RequestMapping(value = "/api/user/public/createaccount", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})

    public ResultDto register(HttpServletRequest request) {
        ResultDto result = new ResultDto();
        JSONObject jObject = new JSONObject();
        try {
            String body = readHttpBody(request);
            logger.info("********createaccount********:" + body);
            JSONObject obj = JSONObject.parseObject(body);
            String username = obj.getString("username");
            String password = obj.getString("password");
            String confirmPs = obj.getString("confirmPassword");
            String agencyId = obj.getString("agencyId");
            if (password.equalsIgnoreCase(confirmPs)) {
                String pwd = UtilsDto.crypt(password);
                logger.debug("register param ::userName:{},password:{},agencyId:{}", username, pwd, agencyId);
                localauthservice.regist(username, pwd, agencyId);
                result.setResultData(true, "用户注册成功", 0, null);
            } else {
                result.setResultData(false, "两次密码输入不匹配", 1, null);
            }

        } catch (Exception e) {
            logger.error("register error :: e,{}", e);
            result.setResultData(false, "用户注册失败", 1, null);
        }
        return result;
    }

    /**
     * 验证账户名字的唯一性
     *
     * @param request username:账户名
     * @return
     */
    @RequestMapping(value = "/api/user/public/checkUserName", method = RequestMethod.POST)
    public ResultDto checkUserName(HttpServletRequest request) {
        JSONObject object = new JSONObject();
        ResultDto result = new ResultDto();
        String body = null;
        try {
            body = readHttpBody(request);
            logger.info("********checkUserName********:" + body);
            JSONObject obj = JSONObject.parseObject(body);
            String username = obj.getString("username");
            boolean flag = userservice.checkUsername(username);
            if (flag) {
                result.setResultData(true, "该账户可以注册", 0, null);
            } else {
                result.setResultData(false, "该用户名已使用", 1, null);
            }
        } catch (IOException e) {
            logger.error("checkUserName error :: {}", e);
            result.setResultData(false, "验证账户名失败", 1, null);
        }
        return result;
    }

    // 生成一个不重复的id
    @RequestMapping(value = "/api/user/public/deviceId", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public String device(HttpServletRequest request) {
        JSONObject info = new JSONObject();
        try {
            JSONObject jObject = new JSONObject();
            String deviceId = localauthservice.device();
            logger.info("********device in********:" + deviceId);
            if (deviceId != null) {
                jObject.put("result", "0");
                jObject.put("deviceId", deviceId);
                jObject.put("msg", "成功 ");
            } else {
                jObject.put("result", "1");
                jObject.put("msg", "deviceId为空");
            }
            logger.info("********device out********:" + deviceId);
            return jObject.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("*****device error******:", e);
            info.put("result", "1");
            info.put("msg", "异常");

        }
        return info.toJSONString();
    }


    /**
     * 用户退出
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/user/public/logout", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public ResultDto Logout(HttpServletRequest request){
        ResultDto result = new ResultDto();
        try {
            String body = readHttpBody(request);
            JSONObject obj = JSONObject.parseObject(body);
            int userId = obj.getInteger("userId");
            int loginType = obj.getInteger("loginType") == null ? 0 : obj.getInteger("loginType");
            String agencyMark = obj.getString("agencyMark");
            localauthservice.Logout(userId, loginType,result,agencyMark);
        } catch (Exception e) {
            logger.error("UserController Logout error,{}", e);
            result.setResultData(false, "登出失败", 1, null);
        }
        return result;
    }

    /**
     * 客户心跳包
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/user/public/heartbeat", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public ResultDto clientHeartbeat(HttpServletRequest request){
        ResultDto result = new ResultDto();
        try {
            String body = readHttpBody(request);
            JSONObject obj = JSONObject.parseObject(body);
            int userId = obj.getInteger("userId");
            String deviceId = obj.getString("deviceId");
            localauthservice.heartbeat(userId, deviceId,result);
        } catch (IOException e) {
            logger.error("UserController clientHeartbeat error,{}", e);
            result.setResultData(false, "查询信息失败", 1, null);
        }
        return result;
    }

    /**
     * 统计在线人数
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/user/public/sonlinenum", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public ResultDto sonlinenum(HttpServletRequest request) {
        ResultDto result = new ResultDto();
        try {
            String body = readHttpBody(request);
            JSONObject obj = JSONObject.parseObject(body);
            int userId = obj.getInteger("userId") == null ? 0 : obj.getInteger("userId");
            String agencyMark = obj.getString("agencyMark");
            localauthservice.sonlinenum(userId,agencyMark,result);
        } catch (Exception e) {
            logger.error("UserController sonlinenum error,{}", e);
            result.setResultData(false, "查询信息失败", 1, null);
        }
        return result;
    }


    /**
     * 用户试玩
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/user/tourbetWaySwitch", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public ResultDto tourbetWay(HttpServletRequest request){
        ResultDto result = new ResultDto();
        try {
            String body = readHttpBody(request);
            JSONObject obj = JSONObject.parseObject(body);
            Integer userId = obj.getInteger("userId");
            Integer lotteyType = obj.getInteger("lotteyType");
            Integer loginType = obj.getInteger("loginType");//0:关闭,1:开启
            userservice.tourbetWaySwitch(userId,lotteyType,loginType,result);
        } catch (Exception e) {
            logger.error("UserController tourbetWaySwitch error,{}", e);
            result.setResultData(false, "试玩失败", 1, null);
        }
        return result;
    }

    /**
     * 修改密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/user/updatePasswordByUserId", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public ResultDto updatePasswordByUserId(HttpServletRequest request){
        ResultDto result = new ResultDto();
        try {
            String body = readHttpBody(request);
            JSONObject obj = JSONObject.parseObject(body);
            String username = obj.getString("username");
            String oldPassword = obj.getString("oldPassword");
            String newPassword = obj.getString("newPassword");
            localauthservice.updatePasswordByUserId(username,oldPassword,newPassword,result);
        } catch (IOException e) {
            logger.error("WealthController updatePasswordByUserId error,{}", e);
            result.setResultData(false, "查询信息失败", 1, null);
        }
        return result;
    }
    
    /**
     * 代理信息查询
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/user/public/delegateInfo", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public ResultDto<Map<String, Object>> delegateInfo(HttpServletRequest request){
        ResultDto<Map<String, Object>> result = new ResultDto<Map<String, Object>>();
        try {
            String body = readHttpBody(request);
            JSONObject obj = JSONObject.parseObject(body);
            int userId = obj.getInteger("userId");
            localauthservice.delegateInfo(result,userId);
        } catch (Exception e) {
            logger.error("UserController clientHeartbeat error,{}", e);
            result.setResultData(false, "查询信息失败", 1, null);
        }
        return result;
    }

    /**
     *查询我的团队
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/user/searchMyTeam", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public ResultDto searchMyTeam(HttpServletRequest request){
        ResultDto result = new ResultDto();
        try {
            String body = readHttpBody(request);
            JSONObject obj = JSONObject.parseObject(body);
            Integer userId = obj.getInteger("userId");
            Integer pageSize = obj.getInteger("pageSize");
            Integer pageNow = obj.getInteger("pageNow");
            localauthservice.searchMyTeam(userId,pageNow,pageSize,result);
        } catch (Exception e) {
            logger.error("UserController searchMyTeam error,{}", e);
            result.setResultData(false, "查询信息失败", 1, null);
        }
        return result;
    }


    /**
     * 推广二维码
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/user/spreadCode", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public ResultDto spreadCode(HttpServletRequest request){
        ResultDto result = new ResultDto();
        try {
            String body = readHttpBody(request);
            JSONObject obj = JSONObject.parseObject(body);
            Integer userId = obj.getInteger("userId");
            localauthservice.spreadCode(userId,result);
        } catch (Exception e) {
            logger.error("UserController spreadCode error,{}", e);
            result.setResultData(false, "查询信息失败", 1, null);
        }
        return result;
    }

    /**
     * 代理商收益
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/user/searchProxyIncome", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public ResultDto searchProxyIncome(HttpServletRequest request){
        ResultDto result = new ResultDto();
        try {
            String body = readHttpBody(request);
            JSONObject obj = JSONObject.parseObject(body);
            String time = obj.getString("time");
            Integer userId = obj.getInteger("userId");
            localauthservice.searchProxyIncome(time,userId,result);
        } catch (Exception e) {
            logger.error("UserController searchProxyIncome error,{}", e);
            result.setResultData(false, "查询信息失败", 1, null);
        }
        return result;
    }

    /**
     * 团队记录
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/user/teamRecord", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8"})
    public ResultDto teamRecord(HttpServletRequest request){
        ResultDto result = new ResultDto();
        try {
            String body = readHttpBody(request);
            JSONObject obj = JSONObject.parseObject(body);
            Integer userId = obj.getInteger("userId");
            Integer pageSize = obj.getInteger("pageSize");
            Integer pageNow = obj.getInteger("pageNow");

            localauthservice.teamRecord(userId,pageSize,pageNow,result);
        } catch (Exception e) {
            logger.error("UserController teamRecord error,{}", e);
            result.setResultData(false, "查询信息失败", 1, null);
        }
        return result;
    }

}


